using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class app_frame_function_register : System.Web.UI.Page
{
    string strPagesetRowID = "b0681c20a144bd1a";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    string refererURL = "";

    protected void Page_init(object sender, EventArgs e)
    {
      //  p_function_register_ft_type_SelectedIndexChanged(null, null);
       // p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);
        
        setRequestURL();

        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                tblcontrols.Visible = false;
                trbtn.Visible = false;
                return;
            }
        }

        //if (Request.UrlReferrer.ToString().IndexOf("DisplayGrid") > 0)
           // refererURL = Request.UrlReferrer.ToString();        
        //loadDynamicControls();
        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
        }
        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);

        if (!Page.IsPostBack)
        {
            loadOwneridDropDown();
        }

        CheckForChangeOwner();
        
        CheckEditOperation();
        //DynamicDisplayI di = new DynamicDisplayI();
        //Control cc = di.FindControl(tblParamters.Controls, "paramLB0");
        //p_help_help_desc.Visible=false;
        
       // p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
        if (!IsPostBack) p_function_register_ft_type_SelectedIndexChanged(null, null);
        if (IsPostBack) return;
        hfParamterCount.Value = "0";
        tblParamters.Visible = false;        
        p_function_register_id.Text = getSeqNumber();
        if (btnUpdate.Visible == true)
        {
            lblHeader.Text = "Function Register - Edit";
            loadMasterValues();
            //p_function_register_ft_type_SelectedIndexChanged(null, null);        
            showParamterContent(true, Request.QueryString["PK"].ToString());
            //loadChildValues();
        }
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                lblHeader.Text = "Function Register - Copy";
                loadMasterValues();
                showParamterContent(true, Request.QueryString["PK"].ToString());
                p_function_register_id.Text = getSeqNumber();
                //p_function_register_owner_id.SelectedValue = Session["user_afrowid"].ToString();
                p_function_register_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_function_register_owner_id.Text = Session["userid"].ToString();
            }
        }


        getpageicons();// Added by srivatsan
        //else
        //    p_function_register_ft_type_SelectedIndexChanged(null, null);        
        isViewMode();
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                HtmlTable ht = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("tblcontrols");
                ddi.disableControls(ht);
                ddi = null;
            }
    }    
    private void loadMasterValues()
    {
        try
        {
            string sPageKey = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from my_function_register where af_row_id='" + sPageKey + "'");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    p_function_register_af_row_id.Value = sPageKey;
                    p_function_register_id.Text = ds.Tables[0].Rows[0]["id"].ToString();
                    p_function_register_fr_name.Text = ds.Tables[0].Rows[0]["fr_name"].ToString();
                    p_function_register_fr_desc.Text = ds.Tables[0].Rows[0]["fr_desc"].ToString();
                    p_function_register_ft_type.SelectedValue = ds.Tables[0].Rows[0]["ft_type"].ToString();
                    p_function_register_ft_type_SelectedIndexChanged(null, null);                    
                    p_function_register_fr_selected_fnExp.SelectedValue = ds.Tables[0].Rows[0]["fr_selected_fnExp"].ToString();
                    //p_function_register_owner_id.SelectedValue = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    p_function_register_owner_id.Value = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    LoadEditPage LEP = new LoadEditPage();
                    txt_p_function_register_owner_id.Text = LEP.GetUserIDFromAfrowid(ds.Tables[0].Rows[0]["owner_id"].ToString());
                    LEP = null;
                    //p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
                }
            }

            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadMasterValues: " + e.Message);
        }
    }
    private void loadChildValues()
    {
        try
        {
            string sPageKey = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from my_fn_register_child where id='" + sPageKey + "'");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int i = 1;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        Label lb = (Label)tblParamters.Rows[i].Cells[0].Controls[0];
                        if (lb.Text == dr["param_name"].ToString())
                        {
                            TextBox tb = (TextBox)tblParamters.Rows[i].Cells[1].Controls[0];
                            tb.Text = dr["param_value"].ToString();
                        }
                        i++;
                    }
                }
            }
            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadChildValues: " + e.Message);
        }
    }
    private void setChildValues()
    {
        try
        {
            string sPageKey = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from my_fn_register_child where af_row_id='" + sPageKey + "'");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int i = 0;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        //Label lb = (Label)tblParamters.Rows[i].Cells[0].Controls[0];
                        //if (lb.Text == dr["param_name"].ToString())
                        //{
                        //    TextBox tb = (TextBox)tblParamters.Rows[i].Cells[1].Controls[0];
                        //    tb.Text = dr["param_value"].ToString();
                        //}
                        Request.Form["paramLB" + i.ToString()] = dr["param_name"].ToString();
                        Request.Form["paramTB" + i.ToString()] = dr["param_value"].ToString();
                        i++;
                    }
                }
            }
            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadChildValues: " + e.Message);
        }
    }
    private DataTable getChildValues(string sPageKey)
    {
        try
        {
            DataTable dt = new DataTable();
            if (sPageKey == "") return dt;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from my_fn_register_child where id='" + sPageKey + "'");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //int i = 0;
                    //foreach (DataRow dr in ds.Tables[0].Rows)
                    //{
                    //    //Label lb = (Label)tblParamters.Rows[i].Cells[0].Controls[0];
                    //    //if (lb.Text == dr["param_name"].ToString())
                    //    //{
                    //    //    TextBox tb = (TextBox)tblParamters.Rows[i].Cells[1].Controls[0];
                    //    //    tb.Text = dr["param_value"].ToString();
                    //    //}
                    //    Request.Form["paramLB" + i.ToString()] = dr["param_name"].ToString();
                    //    Request.Form["paramTB" + i.ToString()] = dr["param_value"].ToString();
                    //    i++;
                    //}
                    dt = ds.Tables[0];
                }
            }
            ds = null;
            hd = null;
            return dt;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadChildValues: " + e.Message);
            return new DataTable();
        }
    }
    private string getSeqNumber()
    {
        int ret = 0;
        HDDatabase hd = new HDDatabase();
        DataSet ds = hd.GetDataset("SELECT max(cast(id as int)+1) AS Count FROM my_function_register");
        if (ds == null)
        {
            ret = 1000;
        }
        else
        {
            try
            {
                ret = Convert.ToInt32(ds.Tables[0].Rows[0]["Count"].ToString());
            }
            catch (Exception e)
            {
            }
            if (ret < 1000)
                ret = ret + 1000;
        }
        hd = null;
        return ret.ToString();
    }
    private bool CheckEditOperation()
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        if (Page.IsPostBack == false)
        {
            if (Request.QueryString["PK"] != null)
            {
                strPageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
            }
            if (IsEdit)
            {
                Master MA = new Master();
                blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
                if (blnStatus == false)
                {
                    strErrMessage = MA.ErrorMessage;
                    Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
                }
            }
        }
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                btnSave.Visible = true;
                btnUpdate.Visible = false;
            }
        }
        else if (Request.QueryString["PK"] == null)
        {
            btnSave.Visible = true;
            btnUpdate.Visible = false;
        }
        else
        {
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }
        return blnStatus;
    }



    private bool SaveData()
    {
        validateOwnerid();
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowID, frmObj, dsePageInfo,true);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }

        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return saveChildRecordScript(false, dseInputInfo.Tables[0].Rows[0]["af_row_id"].ToString(),ref SR);
        //return blnStatus;
    }

    private bool UpdateData()
    {
        validateOwnerid();
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowID, frmObj, dsePageInfo,false);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return saveChildRecordScript(true, p_function_register_af_row_id.Value,ref SR);
        //return blnStatus;
    }
    private void loadDynamicControls()
    {
        //if (IsPostBack) return;
        HiddenField hf = new HiddenField();
        hf.ID = "hf_ref_url";
        //hf.EnableViewState = true;
        if (refererURL.Length > 0) hf.Value = refererURL;
        lbl_message.Controls.Add(hf);                      
    }
    
    private void setValueFromHFField()
    {
        try
        {
            //if (tblParamters.Rows.Count > 1 && tblParamters.Visible == true)
            //    p_function_register_fr_isValidation.Checked = true;
            //else
            //    p_function_register_fr_isValidation.Checked = false;  
            if (p_function_register_ft_type.SelectedValue == "Expression")
            {
                p_function_register_fr_isValidation.Checked = false;
                return;
            }
            HDDatabase hd = new HDDatabase();
            DataSet ds = hd.GetDataset("Select * from my_function where fn_name='" + p_function_register_fr_selected_fnExp.SelectedValue.Replace("'", "''") + "'");
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string code = ds.Tables[0].Rows[0]["fn_code"].ToString();
                    p_function_register_fr_isValidation.Checked = codeHadParameters(code);
                }
            }
            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            p_function_register_fr_isValidation.Checked = false;
        }
    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    private void setRequestURL()//implemented by sanal on 13 Dec 2007
    {
        if (!IsPostBack)
            //hfRequestURL.Value = Request.UrlReferrer.ToString();
            hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
    }
    private string getRefURL()
    {
        string ret = "";
        try
        {
            //DynamicDisplayI di = new DynamicDisplayI();
            //HiddenField hf = (HiddenField)di.FindControl(this.Controls, "hf_ref_url");
            //ret = hf.Value;
            //di = null;
            return hfRequestURL.Value;
        }
        catch (Exception e)
        {
            return "";
        }

    }
    protected void btnSave_ServerClick(object sender, EventArgs e)
    {        
        //return;        
        setValueFromHFField();
        if (SaveData())
        {
            //Response.Write("Data Inserted Successfully");
            //if (saveChildRecordScript(false))
            //{
                string refURL = getRefURL();
                if (refURL.Length > 0)
                    Response.Redirect(refURL);
                else
                    lbl_message.Text = "Data Inserted Successfully";
                p_function_register_id.Text = getSeqNumber();
            //}
            //else
            //    lbl_message.Text = "Unable to save the paramters.";
        }
        else
        {
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error:" + ErrorMessage;
        }
    }
    private bool saveChildRecordScript(bool updateMode,string afRowID,ref ScreenReader sr)
    {
        if (p_function_register_ft_type.SelectedValue == "Expression") return true;
        string paramName = ""; string paramValue = "";
        string query = "";
        try
        {
            HDDatabase hd = new HDDatabase();
            if (updateMode)
            {
                //hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand("delete from my_fn_register_child where af_row_id='" + p_function_register_af_row_id.Value + "'"));
                hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand("delete from my_fn_register_child where id='" + p_function_register_af_row_id.Value.Replace("'", "''") + "'"));
            }
            for (int i = 0; i < Int32.Parse(hfParamterCount.Value); i++)
            {
                paramName = Request.Form["paramLB" + i.ToString()];
                paramValue = Request.Form["paramTB" + i.ToString()];
                //query = "insert into my_fn_register_child(af_row_id,id,param_name,param_value) values ('" + afRowID + "','" + p_function_register_id.Text + "','" + paramName + "','" + paramValue + "')";
                query = "insert into my_fn_register_child(af_row_id,id,param_name,param_value) values ('" + sr.getHashKey() + "','" + afRowID + "','" + paramName.Replace("'", "''") + "','" + paramValue.Replace("'", "''") + "')";
                hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand(query));
            }
            hd = null;
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private bool saveChildRecords(bool updateMode)
    {
        if (p_function_register_ft_type.SelectedValue == "Expression") return true;
        string paramName = ""; string paramValue = "";
        string query = "";
        try
        {
            HDDatabase hd = new HDDatabase();
            if (updateMode)
                hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand("delete from my_fn_register_child where af_row_id='" + p_function_register_id.Text.Replace("'", "''") + "'"));
            for (int i = 1; i < tblParamters.Rows.Count; i++)
            {
                //DynamicDisplayI di = new DynamicDisplayI();
                //Control cc = di.FindControl(tblParamters.Controls, "paramLB" + i.ToString());
                Label lb = (Label)tblParamters.Rows[i].Cells[0].Controls[0];
                paramName = lb.Text;
                TextBox tb = (TextBox)tblParamters.Rows[i].Cells[1].Controls[0];
                paramValue = tb.Text;
                query = "insert into my_fn_register_child(af_row_id,id,param_name,param_value) values ('" + p_function_register_id.Text + "','" + paramName.Replace("'", "''") + "','" + paramValue.Replace("'", "''") + "')";
                hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand(query));
            }
            hd = null;
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private string checkForErrors(string content, bool isExpression)
    {
        MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();            
        try
        {            
            sc.Language = "VBScript";
            if (!isExpression)
                sc.AddCode(content);
            else
                sc.Eval(content);
            sc = null;
            return "success";
        }
        catch (Exception e)
        {
            sc = null;
            return e.Message;
        }
    }
    private int getFunctionCount(string content)
    {
        MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();            
        MSScriptControl.Procedures pr;
        int ret=0;
        try
        {            
            sc.Language = "VBScript";
            sc.AddCode(content);
            pr = sc.Procedures;
            ret = pr.Count;
            sc = null;            
        }
        catch (Exception e)
        {
            sc = null;
            ret = -1;
        }
        return ret;
    }
    private void addTextBox(string controlID,string value)
    {
        TextBox tb = new TextBox();
        tb.ID = controlID;
        tb.Text = value;
        if (frmObj!=null) frmObj.Controls.Add(tb);
    }
    protected void btnUpdate_ServerClick(object sender, EventArgs e)
    {
        setValueFromHFField();
        if (UpdateData())
        {
            //if (saveChildRecordScript(true))
            //{
                string refURL = getRefURL();
                if (refURL.Length > 0)
                    Response.Redirect(refURL);
                else
                    lbl_message.Text = "Data Updated Successfully";
            //}
            //else
            //    lbl_message.Text = "Unable to save the paramters.";
        }
        else
        {
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. Error:" + ErrorMessage;
        }
    }    
    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }

    protected void p_function_register_ft_type_SelectedIndexChanged(object sender, EventArgs e)
    {        
        //p_function_register_fr_selected_fnExp
        lblAvaliable.Text = p_function_register_ft_type.SelectedValue == "Expression" ? "Available Expressions" : "Available Functions";
        HDDatabase hd = new HDDatabase();
        DataSet ds = hd.GetDataset("Select * from my_function where fn_type='" + p_function_register_ft_type.SelectedValue.Replace("'", "''") + "'");
        p_function_register_fr_selected_fnExp.Items.Clear();
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                clearAll();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    p_function_register_fr_selected_fnExp.Items.Add(new ListItem(dr["fn_name"].ToString(),dr["fn_name"].ToString()));
                }
            }
        }
        //p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
        showParamterContent(false,"");
    }
    protected void dummy_SelectedIndexChanged(object sender, EventArgs e)
    {
        showParamterContent(false,null);
    }
    private void showParamterContent(bool showData,string id)
    {
        hfParamterCount.Value = "0";string arguments="";
        DataTable dtData = new DataTable();
        if (showData && id.Trim()!="") dtData = getChildValues(id);
        if (p_function_register_ft_type.SelectedValue == "Expression")
        {
            lblDynamicContent.Text = "";
            return;
        }
        string content = "<table cellpadding='2' cellspacing='0' width='100%'>";
        content += "<tr><td class='Dynamic_PageHeaderRow'>Parameters</td><td class='Dynamic_PageHeaderRow'>Parameter Value</td><tr>";
        //if (p_function_register_ft_type.SelectedValue == "Expression")
        //{
        //    content += "<tr><td colspan='2'>No Paramters to be defined</td></tr>";
        //}
        //else
        {
            HDDatabase hd = new HDDatabase();
            string name_id = ""; string args_id = ""; string value = "";
            DataSet ds = hd.GetDataset("Select * from my_function where fn_name='" + p_function_register_fr_selected_fnExp.SelectedValue.Replace("'", "''") + "'");
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string code = ds.Tables[0].Rows[0]["fn_code"].ToString();
                    int functionPos = code.ToLower().IndexOf("function");
                    string fnName = "";
                    arguments = "";
                    string[] args;
                    if (functionPos > -1)
                    {
                        functionPos = functionPos + "function".Length;
                        fnName = code.Substring(functionPos, code.IndexOf("(") - functionPos);
                        functionPos = code.IndexOf("(");
                        arguments = code.Substring(functionPos + 1, code.IndexOf(")") - functionPos - 1);

                        if (arguments.Length > 0)
                        {
                            args = arguments.Split(',');
                            for (int i = 0; i < args.Length; i++)
                            {
                                value = "";
                                name_id = "paramTB" + i.ToString();
                                args_id = "paramLB" + i.ToString();
                                if (showData && id.Trim() != "")
                                {
                                    try
                                    {
                                        value = dtData.Select("param_name='" + args[i].ToString().Trim() + "'")[0]["param_value"].ToString();
                                        value += " value='" + value + "' ";
                                    }
                                    catch (Exception e)
                                    { }
                                }
                                if (Request.QueryString["VMODE"] != null)
                                {
                                    if (Request.QueryString["VMODE"].ToString() == "1")
                                    {
                                        content += "<tr><td class='defaultFont'><font size='2px'>" + args[i].ToString().Trim() + "</font></td><td><input type='hidden' disabled='disabled' name='" + args_id + "' id='" + args_id + "' value='" + args[i].ToString().Trim() + "' /><input type='text' disabled='disabled' name='" + name_id + "' id='" + name_id + "'" + value + " />" + getDropDownScript(i, true) + "</td></tr>";
                                    }
                                }
                                else
                                {
                                    content += "<tr><td class='defaultFont'><font size='2px'>" + args[i].ToString().Trim() + "</font></td><td><input type='hidden' name='" + args_id + "' id='" + args_id + "' value='" + args[i].ToString().Trim() + "' /><input type='text' name='" + name_id + "' id='" + name_id + "'" + value + " />" + getDropDownScript(i, false) + "</td></tr>";
                                }
                                //content += "<tr><td><font face='Arial' size='2px'>" + args[i].ToString().Trim() + "</font></td><td><input type='hidden' name='" + args_id + "' id='" + args_id + "' value='" + args[i].ToString().Trim() + "' /><input type='text' name='" + name_id + "' id='" + name_id + "'" + value + " />" + getDropDownScript(i) + "</td></tr>";
                            }
                            hfParamterCount.Value = args.Length.ToString();
                        }
                        else
                            content += "<tr><td colspan='2'>No Parameters specified.</td></tr>";
                    }
                }               
            }
            //content += "<td class='Dynamic_PageHeaderRow'>Parameters</td><td class='Dynamic_PageHeaderRow'>Parameter Value</td>";
        }
        content += "</table>";
        lblDynamicContent.Text = arguments.Trim().Length>0 ? content : "";
    }
    private void resetValue(ControlCollection cc)
    {
    
    }
    private void clearAll()
    {
        int count = 0;
        
        for (int i = 1; i < tblParamters.Rows.Count; i++)
        {
            Control c = tblParamters.Rows[i].Cells[0].Controls[0];
            if (c != null) c.Dispose();
            c = tblParamters.Rows[i].Cells[1].Controls[0];
            if (c != null) c.Dispose();
        }
        for (int j = 1; j < tblParamters.Rows.Count; j++)
        {
            tblParamters.Rows.RemoveAt(j - count); count++;
        }
    }
    protected void p_function_register_fr_selected_fnExp_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (IsPostBack) return;        
        int count = 0;
        if (p_function_register_ft_type.SelectedValue == "Expression")
        {            
            for (int j = 1; j < tblParamters.Rows.Count; j++)
            {
                tblParamters.Rows.RemoveAt(j - count); count++;
            }
            tblParamters.Visible = false;
            return;
        }
        clearAll();
        //tblParamters.Visible = false;
        HDDatabase hd = new HDDatabase();
        DataSet ds = hd.GetDataset("Select * from my_function where fn_name='" + p_function_register_fr_selected_fnExp.SelectedValue.Replace("'", "''") + "'");        
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                string code = ds.Tables[0].Rows[0]["fn_code"].ToString();                
                int functionPos = code.ToLower().IndexOf("function");
                string fnName = "";
                string arguments = "";
                string[] args;
                if ( functionPos > -1)
                {                    
                    functionPos = functionPos + "function".Length;
                    fnName = code.Substring(functionPos, code.IndexOf("(") - functionPos);
                    functionPos = code.IndexOf("(");
                    arguments = code.Substring(functionPos + 1, code.IndexOf(")") - functionPos-1);

                    HtmlTable ht = new HtmlTable();
                    ht.EnableViewState = true;
                    ht.ID = "DynamicTable";
                    if (arguments.Length > 0)
                    {
                        args = arguments.Split(',');
                        //addControls(args);
                        for (int i = 0; i < args.Length; i++)
                        {
                            TableRow hr = new TableRow();
                            hr.ID = "Row" + i.ToString();
                            hr.EnableViewState = true;
                            TableCell hc1 = new TableCell();
                            hc1.ID = "cell1" + i.ToString();
                            hc1.EnableViewState = true;
                            hc1.Controls.Add(getLabel("paramLB" + i.ToString(), args[i].ToString()));
                            TableCell hc2 = new TableCell();
                            hc2.ID = "cell2" + i.ToString();
                            hc2.EnableViewState = true;
                            hc2.Width = 30;
                            hc2.Controls.Add(getTextBox("paramTB" + i.ToString()));// = ;
                            TableCell hc3 = new TableCell();
                            hc3.ID = "cell3" + i.ToString();
                            hc3.EnableViewState = true;
                            //hc3.
                            hc3.Controls.Add(getDropDownBox("paramDD" + i.ToString()));// = ;
                            hr.Cells.AddRange(new TableCell[] { hc1, hc2, hc3 });
                            tblParamters.Rows.Add(hr);

                            //TableRow hr = new TableRow();
                            //hr.ID = "Row" + i.ToString();
                            //hr.EnableViewState = true;                            
                            //TableCell hc1 = new TableCell();
                            //hc1.ID = "cell1" + i.ToString();
                            //hc1.EnableViewState = true;
                            //hc1.Controls.Add(getLabel("paramLB" + i.ToString(), args[i]));
                            //TableCell hc2 = new TableCell();
                            //hc2.ID = "cell2" + i.ToString();
                            //hc2.EnableViewState = true;
                            //hc2.Controls.Add(getTextBox("paramTB" +i.ToString()));// = ;
                            //TableCell hc3 = new TableCell();
                            //hc3.ID = "cell3" + i.ToString();
                            //hc3.EnableViewState = true;
                            ////hc3.
                            //hc3.Controls.Add(getDropDownBox("paramDD" + i.ToString()));// = ;
                            //hr.Cells.AddRange(new TableCell[] { hc1, hc2,hc3 });
                            //tblParamters.Rows.Add(hr);


                            //HtmlTableRow hhr = new HtmlTableRow();
                            //hhr.ID = "HRow" + i.ToString();
                            //hhr.EnableViewState = true;
                            //HtmlTableCell hhc1 = new HtmlTableCell();
                            //hhc1.ID = "Hcell1" + i.ToString();
                            //hhc1.EnableViewState = true;
                            //hhc1.Controls.Add(getLabel("HparamLB" + i.ToString(), args[i]));
                            //HtmlTableCell hhc2 = new HtmlTableCell();
                            //hhc2.ID = "Hcell2" + i.ToString();
                            //hhc2.EnableViewState = true;
                            //hhc2.Controls.Add(getTextBox("HparamTB" + i.ToString()));// = ;
                            //HtmlTableCell hhc3 = new HtmlTableCell();
                            //hhc3.ID = "Hcell3" + i.ToString();
                            //hhc3.EnableViewState = true;
                            ////hc3.
                            //hhc3.Controls.Add(getDropDownBox("HparamDD" + i.ToString()));// = ;
                            ////hhr.Cells.AddRange(new HtmlTableCell[] { hhc1, hhc2, hhc3 });
                            //hhr.Cells.Add(hhc1);
                            //hhr.Cells.Add(hhc2);
                            //hhr.Cells.Add(hhc3);                            
                            //ht.Rows.Add(hhr);
                        }
                        ht.Visible = true;
                        tblParamters.Visible = true;
                    }
                    
                    //DynamicDisplayI dd = new DynamicDisplayI();
                    //dd.FindControl(frmObj.Controls,"DynamicControl").Controls.Add(ht);
                    //ttTest.Rows[0].Cells[0].Controls.Add(ht);
                    
                }
                else
                    tblParamters.Visible = false;
            }
        }
    }
    
    private bool codeHadParameters(string code)
    {
        if (code.Length < 1) return false;
        MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
        MSScriptControl.Procedures pr;
        bool temp = false;
        try
        {
            sc.Language = "VBScript";
            sc.AddCode(code);
            pr = sc.Procedures;
            for (int i = 1; i < pr.Count + 1; i++)
            {
                if (pr[i].HasReturnValue)
                {
                    temp = true;
                    break;
                }
            }            
            pr = null;
            sc = null;
            return temp;
        }
        catch (Exception e)
        {
            sc = null;
            return false;
        }
    }
    private void addControls(string[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            TableRow hr = new TableRow();
            hr.ID = "Row" + i.ToString();
            hr.EnableViewState = true;
            TableCell hc1 = new TableCell();
            hc1.ID = "cell1" + i.ToString();
            hc1.EnableViewState = true;
            hc1.Controls.Add(getLabel("paramLB" + i.ToString(), args[i]));
            TableCell hc2 = new TableCell();
            hc2.ID = "cell2" + i.ToString();
            hc2.EnableViewState = true;
            hc2.Controls.Add(getTextBox("paramTB" + i.ToString()));// = ;
            TableCell hc3 = new TableCell();
            hc3.ID = "cell3" + i.ToString();
            hc3.EnableViewState = true;
            //hc3.
            hc3.Controls.Add(getDropDownBox("paramDD" + i.ToString()));// = ;
            hr.Cells.AddRange(new TableCell[] { hc1, hc2, hc3 });
            tblParamters.Rows.Add(hr);
        }
    }
    private Control getLabel(string id,string text)
    {
        Label lb = new Label();
        lb.ID = id;
        lb.Text = text;
        lb.EnableViewState = true;
        //tb.Font = "Arial";
        return lb;
    }
    private Control getTextBox(string id)
    {
        TextBox tb = new TextBox();
        tb.MaxLength = 20;
        tb.EnableViewState = true;
        tb.ID = id;        
        //tb.Font = "Arial";
        return tb;
    }
    protected void dd_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            DropDownList dls = (DropDownList)sender;
            //if (dls.SelectedIndex == 0) return;
            string ss = dls.ID;
            ss = "paramTB" + ss.TrimStart("paramDD".ToCharArray());            
            DynamicDisplayI di = new DynamicDisplayI();
            Control cc = di.FindControl(this.Form.Controls, ss);
            di = null;
            TextBox tb = (TextBox)cc;
            if (dls.SelectedIndex == 0)
                tb.Text = "";
            else
                tb.Text = "{!" + dls.SelectedValue + "}";
        }
        catch (Exception ee)
        {

        }
    }
    private Control getDropDownBox(string id)
    {
        DropDownList dd = new DropDownList();
        dd.SelectedIndexChanged+=new EventHandler(dd_SelectedIndexChanged);
        dd.ID = id;        
        dd.EnableViewState = true;
        dd.AutoPostBack = true;      
        //get system variables and load here
        dd.Items.Add(new ListItem("-- Select System Variables --", "-- Select System Variables --"));
        HDDatabase hd = new HDDatabase();
        DataSet ds = new DataSet();
        ds = hd.GetDataset("Select distinct sy_var_name from sy_var");
        hd = null;
        if (ds.Tables.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                dd.Items.Add(new ListItem(dr["sy_var_name"].ToString(), dr["sy_var_name"].ToString()));
            }
        }
        return dd;
    }
    private string getDropDownScript(int count,bool disable)
    {
        string ret = "";
        string id = "DR_" + count.ToString();
        if(disable)
        ret = "<select disabled='disabled' onchange='javascript:loadSystem(" + count.ToString() + ");' name='" + id + "' id='" + id + "'>";
        else
        ret = "<select onchange='javascript:loadSystem(" + count.ToString() + ");' name='" + id + "' id='" + id + "'>";
        ret += "<option value='-- Select System Variables --'>-- Select System Variables --</option>"; 
        HDDatabase hd = new HDDatabase();
        DataSet ds = new DataSet();
        ds = hd.GetDataset("Select distinct sy_var_name from sy_var");
        hd = null;
        if (ds.Tables.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ret += "<option value='"+dr["sy_var_name"].ToString()+"'>" + dr["sy_var_name"].ToString() + "</option>";
            }
        }
        ret += "</select>";
        return ret;
    }
    protected void btnReset_ServerClick(object sender, EventArgs e)
    {
        try
        {
            //string refURL = getRefURL();
            //if (refURL.Length > 0)
            //    Response.Redirect(refURL);
            //else
            {
                p_function_register_fr_desc.Text = "";
                p_function_register_fr_name.Text = "";
                p_function_register_fr_selected_fnExp.SelectedIndex = 0;
                p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
                p_function_register_ft_type.SelectedIndex = 0;
                lblDynamicContent.Text = "";
            }
        }
        catch (Exception ee)
        { }
    }
    private void getpageicons()
    {
        PageIcons icons = new PageIcons();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();

            lblHeader.Text = "&nbsp;" + icons.geticontextfrompageset(strPagesetRowID, 2) + "&nbsp;" + lblHeader.Text;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            lblHeader.Text = "<img src="+PageIcons.strdefaulticon.ToString()+"></img>&nbsp;" + lblHeader.Text;
        }
        finally
        {
            icons = null;
            Hdd = null;
        }

    }
    #region loadownerid
    //private void loadOwneridDropDown() // Added by srivatsan for owner id change
    //{
    //    HDDatabase Hdd = new HDDatabase();
    //    BindControl BC = new BindControl();
    //    //DataSet ds = new DataSet();
    //    DataTable dt = null;
    //    try
    //    {
    //        string strBindRowID = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
    //        BC.Bind(strBindRowID, p_function_register_owner_id, ref dt);

    //        if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
    //        {
    //            p_function_register_owner_id.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
    //        }

    //        if (Request.QueryString["PK"] == null)
    //        {
    //            p_function_register_owner_id.SelectedValue = Session["user_afrowid"].ToString();
    //        }
    //        if (Request.QueryString["PK"] != null)
    //        {
    //            if (Request.QueryString["CPY"] != null)
    //            {
    //                p_function_register_owner_id.SelectedValue = Session["user_afrowid"].ToString();
    //            }

    //        }

    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
    //    }
    //    finally
    //    {
    //        Hdd = null;
    //        BC = null;
    //        dt = null;
    //    }


    //}
    #endregion

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {

            if (Request.QueryString["PK"] == null)
            {
                
                p_function_register_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_function_register_owner_id.Text = Session["userid"].ToString();

            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    p_function_register_owner_id.Value = Session["user_afrowid"].ToString();
                    txt_p_function_register_owner_id.Text = Session["userid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }

    
    private bool validateOwnerid()
    {
        bool status = false;
        BindControl BC = new BindControl();
        HDDatabase HDD = new HDDatabase();
        DataSet dsBind = new DataSet();
        string sql = BC.GetBindSql("f496930dfe0b690f");
        dsBind = HDD.GetDataset(sql);
        if (dsBind != null)
        {
            if (dsBind.Tables.Count > 0)
            {
                if (dsBind.Tables[0].Rows.Count > 0)
                {
                    DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_p_function_register_owner_id.Text.Trim().Replace("'", "''") + "'");

                    if (drrbind.Length > 0)
                    {
                        p_function_register_owner_id.Value = drrbind[0]["val"].ToString();
                        status = true;
                    }
                }
            }
        }
        if (status != true)
        {
            //lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Invalid data for Owner :" + txt_ownerid.Text;
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Invalid data for Owner :" + HttpUtility.HtmlEncode(txt_p_function_register_owner_id.Text);

        }
        return status;

    }
    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {
                imgOwnerSearch.Visible = false;
                txt_p_function_register_owner_id.Enabled = false;
            }
            sec = null;
        }
        catch
        {

        }
    }

    private void FindControlandDisable()
    {
        try
        {
            foreach (Control cn in lblDynamicContent.Controls)
            {
                string id = cn.ID;
            }
        }
        catch
        {
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
}
